package com.zivwu.library;


import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.support.v4.content.ContextCompat;

import com.zivwu.library.ann.PerApp;

import java.io.File;

import javax.inject.Inject;
import javax.inject.Named;

import dagger.Module;
import dagger.Provides;

@Module
@PerApp
public class AppModule {
    private Context context;

    @Inject
    public AppModule(Context context) {
        this.context = context;
    }

    @Provides
    @PerApp
    Context providerContext() {
        return context;
    }


    @Named("cacheFile")
    @PerApp
    @Provides
    File providerCacheFile(Context context) {
        File storageDir;

        String[] permissions ;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
            permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
        } else {
            permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
        }

        if (hasPermission(permissions)) {
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                storageDir = context.getExternalCacheDir();
            } else {
                storageDir = context.getCacheDir();
            }
        } else {
            storageDir = context.getCacheDir();
        }
        return storageDir;
    }

    private boolean hasPermission(String[] permissions) {
        boolean denied = true;
        for (String permission : permissions) {
            denied = denied & hasPermission(permission);
        }
        return denied;
    }

    private boolean hasPermission(String permission) {
        return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
    }

}
